﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Radovici.Ctrls.Desktop;
using Radovici.SharedLibrary;

namespace Radovici.Ctrls.ContentControls
{
    public static class ModalHelper
    {
        public static void Show(this UIElement ctrl, CancelEventHandler callback)
        {
            Show(ctrl, callback, null);
        }

        public static void Show(this UIElement ctrl, CancelEventHandler callback, UIElement anchor)
        {
            var dlg = new Modal()
                          {
                              Content = ctrl,
                              IsDragPermanent = true
                          };
            if (callback != null)
            {
                dlg.Closed += callback;
            }
            dlg.Show(anchor);
            dlg.Anchor(anchor);
            dlg.Loaded += new RoutedEventHandler(OnModalLoaded);            
        }

        private static void OnModalLoaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("OnModalLoaded");
        }

        public static void Anchor(this FrameworkElement ctrl, UIElement anchor)
        {
            var root = Application.Current.RootVisual as FrameworkElement;
            if (root != null)
            {
                if (anchor != null)
                {
                    GeneralTransform gt = anchor.TransformToVisual(root);
                    Point offset = gt.Transform(new Point(0, 0));
                    double controlLeft = offset.X;
                    double controlTop = offset.Y;
                    Canvas.SetLeft(ctrl, controlLeft);
                    Canvas.SetTop(ctrl, controlTop);
                }
                if (Canvas.GetLeft(ctrl) + ctrl.ActualWidth > root.Width)
                {
                    Canvas.SetLeft(ctrl, root.Width - ctrl.ActualWidth);
                }
                if (Canvas.GetTop(ctrl) + ctrl.ActualHeight > root.Height)
                {
                    Canvas.SetTop(ctrl, root.Height - ctrl.ActualHeight);
                }
            }
        }
    }
}
